import React from 'react';
import { observer } from 'mobx-react';
import { Input } from 'antd';
import jQuery from 'jquery';
import { formatFloatValue } from '../../../../util/modeUtil';

interface Props {
    value?: string;
    defaultValue?: string;
    onBlur: (string) => void;
    fieldhtmltype?:any,
    viewAttr:string;
    fieldtype?:any,
    reg: RegExp;
    qfws?;
    max?;
    min?;
}
export class IntegerInput extends React.Component<Props, any> {
    constructor(props: Props) {
        super(props);
        this.state={value:this.props.value};
    }
    formatter = (fieldhtmltype,fieldtype,val?: string | number) => {
        const { qfws = 2  } = this.props;
        let _value = val ? `${val}` : ``;
        if (_value.endsWith(".")) {
            _value += "0";
        }
        _value = jQuery.trim(_value).length > 0 ? _value.replace(/\,/g, '') : '';
        if(fieldhtmltype=='1'&&fieldtype=='5'){
            return formatFloatValue(_value, qfws, true);
        }else{
            return formatFloatValue(_value, qfws, false);
        }
    }

    onChange = (e) => {
        const { value } = e.target;
        const { reg,max,min } = this.props;
        if ((!isNaN(value) && reg.test(value)) || value === '' || value === '-') {
            const intValue = (value === '' || value === '-') ? value : value;
            if(max&&intValue>max||min&&intValue<min)return;
            this.setState({value:intValue});
        }
    }
    onBlur = (e) => {
       const { value } = e.target;
        const { reg,onBlur} = this.props;
        const {fieldhtmltype,fieldtype}=this.props;
        if ((!isNaN(value) && reg.test(value)) || value === '' || value === '-') {
            let intValue = (value === '' || value === '-') ? value : value;
            intValue = this.formatter(fieldhtmltype,fieldtype,intValue);
            onBlur(intValue);
        }
    }

    componentWillReceiveProps(nextProps){
        this.state={value:nextProps.value};
    }

    render() {
        const {viewAttr}=this.props;
        return <div  style={{float:'left'}}>
            {viewAttr=='2'?<Input
                {...this.props}
                value={this.state.value}
                onBlur={this.onBlur}
                onChange={this.onChange}
            />:this.state.value}
            </div>
    }
}

export default observer((props: Props) => {
    return (
        <IntegerInput {...props} /> 
    )
});
